package com.sihai.ehr.service.impl;

import com.sihai.core.*;
import com.sihai.ehr.model.biz.SalaryPerformance;
import com.sihai.ehr.service.SalaryPerformanceService;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.List;

/**
 * author: wxn
 * since: 13-1-16 Time: 上午10:57
 * 绩效奖金管理Service
 */
@Service("salaryPerformanceService")
public class SalaryPerformanceServiceImpl implements SalaryPerformanceService {
    @Resource
    private DataAccessor dataAccessor;

    @Override
    public SalaryPerformance get(Long id) {
        Assert.notNull(id, "salary performance id is required");
        return dataAccessor.get(SalaryPerformance.class, id);
    }

    @Override
    public void save(SalaryPerformance performance) {
        Assert.notNull(performance, "salary performance is required");
        dataAccessor.save(performance);
    }

    @Override
    public void delete(final String ids) {
        dataAccessor.batchUpdate(new QueryCreator() {
            @Override
            public Query createQuery(Session session) {
                return session.createQuery(String.format("delete from SalaryPerformance p where p.id in (%s)", ids));
            }
        });
    }

    @Override
    public LimitedList<SalaryPerformance> find(Long organizationId, Limit limit, Sorter sorter) {
        if(organizationId == null){
            return dataAccessor.findByHql(SalaryPerformance.class, "from SalaryPerformance'", null, limit, sorter);
        }
        return dataAccessor.findByHql(SalaryPerformance.class, "from SalaryPerformance p where p.organization.id = ?", new Object[]{organizationId}, limit, sorter);
    }

    //检查上下标是否跨某个区间
    @Override
    public boolean check(SalaryPerformance performance) {
        Assert.notNull(performance, "salary performance is required");
        String temp = "";
        if(performance.getId() != null && performance.getId() > 0){
            temp = " and p.id <> "+performance.getId().longValue();
        }
        //检查上标是否跨某个区间
        List<Long> list = dataAccessor.findByHql(Long.class, "select p.id from SalaryPerformance p where p.scoreEnd >= ? and p.scoreStart <= ? and p.organization.id=?"+temp, new Object[]{performance.getScoreEnd(), performance.getScoreEnd(), performance.getOrganization().getId()}, null, null);
        if(list != null && !list.isEmpty()){
            return false;
        }
        //检查下标是否跨某个区间
        list = dataAccessor.findByHql(Long.class, "select p.id from SalaryPerformance p where p.scoreEnd >= ? and p.scoreStart <= ? and p.organization.id=?"+temp, new Object[]{performance.getScoreStart(), performance.getScoreStart(), performance.getOrganization().getId()}, null, null);
        if(list != null && !list.isEmpty()){
            return false;
        }
        return true;
    }
}
